#!/bin/bash
(
    cd /app

    RETRIES=300 # 5 minutes
    until psql -h ${POSTGRES_HOST} -U ${POSTGRES_USER} -d ${POSTGRES_DB} -c "select 1" > /dev/null 2>&1 || [ $RETRIES -eq 0 ]; do
      echo "Waiting for postgres server, $((RETRIES--)) remaining attempts..."
      sleep 1
    done

    echo "PostgreSQL is up and running"

    psql -h ${POSTGRES_HOST} -U ${POSTGRES_USER} -d ${POSTGRES_DB} -c 'CREATE SCHEMA IF NOT EXISTS postgis; DROP EXTENSION postgis CASCADE;'
    psql -h ${POSTGRES_HOST} -U ${POSTGRES_USER} -d ${POSTGRES_DB} -c 'CREATE EXTENSION IF NOT EXISTS postgis SCHEMA postgis;'
    psql -h ${POSTGRES_HOST} -U ${POSTGRES_USER} -d ${POSTGRES_DB} -c 'CREATE EXTENSION IF NOT EXISTS "uuid-ossp" SCHEMA postgis;'
    psql -h ${POSTGRES_HOST} -U ${POSTGRES_USER} -d ${POSTGRES_DB} -c 'CREATE EXTENSION IF NOT EXISTS "unaccent" SCHEMA postgis;'

    cp -f test/ci/database.yml config/database.yml

    gpg --import 'test/fixture-files/my-private-key.asc'

    echo "GPG keys list:"
    gpg --list-keys

    bundle exec rake db:migrate RAILS_ENV=test VERBOSE=false

    bundle exec rake ${1:-test}
)
